<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Category extends CI_Model {

    private $CI;
    
    function __construct() {
        parent::__construct();
    }
    
    function get_all() {
    	return $this
    		->db
    		->get('category')
    		->result();
    }
    
    function insert($names,$parent_id,$color) {
    	$this->load->model('language');
    	$languages = $this->language->get_all();
    	
    	foreach ($languages as $language)
    		$this->db->query("ALTER TABLE category ADD name_$language->id TEXT");
    	
    	$data['parent_id'] = $parent_id;
    	foreach ($names as $language_id=>$name) 
    		$data['name_'.$language_id] = mysql_real_escape_string($name);

    	$data['color'] = $color;

    	$this
    		->db
    		->insert('category',$data);
    		
    	//TODO error
    	
    }

    function update($cat_id,$names,$parent_id,$color) {
    	$this->load->model('language');
    	$languages = $this->language->get_all();
    	
    	foreach ($languages as $language)
    		$this->db->query("ALTER TABLE category ADD name_$language->id TEXT");
    	
    	$data['parent_id'] = $parent_id;
    	foreach ($names as $language_id=>$name) 
    		$data['name_'.$language_id] = mysql_real_escape_string($name);
    	
    	$data['color'] = $color;

    	$this
    		->db
    		->where('id',$cat_id)
    		->update('category',$data);
   	}

    function delete($cat_id) {
    	//find parent of cat to delete
    	$parent_id = $this->db->where('id',$cat_id)->select('parent_id')->get('category')->row()->parent_id;
		if ($this->db->_error_number()!=0)
			throw new Exception('Error: '.$this->db->_error_number().': '.$this->db->_error_message());
    	
    	//set this parent to all children of cat to delete
    	$this->db->where('parent_id',$cat_id)->update('category',array('parent_id'=>$parent_id));
		if ($this->db->_error_number()!=0)
			throw new Exception('Error: '.$this->db->_error_number().': '.$this->db->_error_message());
    	
    	//delete specified cat
    	$this->db->where('id',$cat_id)->delete('category');
    			
		if ($this->db->affected_rows() == 0)
			throw new Exception("Category #$cat_id not found");
	}
    
    

}?>